package org.dragonnova.meetingclient.client.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ztspeech.AZTClient;

import org.dragonnova.meetingclient.R;
import org.dragonnova.meetingclient.client.service.WIFIService;
import org.dragonnova.meetingclient.core.manager.UdpManager;
import org.dragonnova.meetingclient.core.net.SocketUtils;
import org.dragonnova.meetingclient.model.bean.VoiceInfo;
import org.dragonnova.meetingclient.client.service.TranslationService;
import org.dragonnova.meetingclient.utils.Constants;
import org.dragonnova.meetingclient.utils.LogUtil;
import org.dragonnova.meetingclient.utils.PromptUtil;
import org.dragonnova.meetingclient.utils.ToastUtil;

import java.util.ArrayList;

public class MainActivity extends Activity implements ServiceConnection {

    private static final String TAG = MainActivity.class.getName();

    private static final int KEY_RECORD_ACTION = 225;
    private static final int KEY_LANGUAGE_ACTION = 226;
    private static final int KEY_VOLUME_DOWN = 223;
    private static final int KEY_VOLUME_UP = 224;
    private static final int KEY_POWER_DOWN = 26;
    private static final int DELAY = 30 * 60 * 1000;
    private static final int TONE_LENGTH_MS = 150;
    //显示现在的wifi和录音状况
    private TextView wifiTxtView;
    private TextView recordTxtView;
    //显示识别和翻译的结果
    private TextView mainTvOrigin;
    private ImageView mainIvRecord;
    //说话的按钮（为了增大点击区域，使用父布局）
    private RelativeLayout mainRlRecord;
    //中英文切换按钮
    private RadioButton ivBtnCH;
    private RadioButton ivBtnEN;
    //跳转到设置界面的按钮
    private RelativeLayout mainRlSwitch;
    private TextView mainTvSwitch;
    //电池图标
    private ImageView mainIvBattery;
    private TextView mainTvBattery;
    //设置界面的控件
    private RadioGroup settingsRgSwitch;
    private ImageView settingsIvBack;
    private RelativeLayout settingsRlBack;
    private RadioButton settingsBtCh;
    private RadioButton settingsBtEn;
    private ImageView mainIvCircle;
    //dialog
    private Dialog switchDialog;

    public static final ArrayList<IBinder> services = new ArrayList<>();

    //音量管理
    private AudioManager audioManager;
    //蓝牙适配器
    private BluetoothAdapter bluetoothAdapter;
    //蓝牙管理
    private BluetoothManager bluetoothManager;
    //翻译服务
    private TranslationService.MyBinder transBinder;
    private TranslationService transService;
    //wifi服务
    private WIFIService wifiService;
    private WIFIService.WifiBinder wifiBinder;
    //中文还是英文的标记
    private boolean isCH2EN;
    //关机
    private boolean poweroff = false;
    private boolean wifiExit = false;
    //电源锁
    private PowerManager.WakeLock mWakeLock = null;
    //由于keyup的时候系统还没有返回值，所以需要判断是否已经松开
    private boolean isKeyUp = true;

    private AnimatorSet onClickDownAnimationSet;
    private AnimatorSet onClickUpAnimationSet;
    private AnimatorSet permitAnimationSet;

    //电池监听
    private IntentFilter mBatteryFilter;

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            switch (what) {
                case 100:
                    mainRlRecord.setClickable(true);
                    mainRlRecord.setEnabled(true);
                    break;
                case 101:
                    if (!isKeyUp) {
                        if (wifiBinder != null) {
                            wifiBinder.requestVoicePersist();
                        }
                        this.sendEmptyMessageDelayed(101, 300);
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (getActionBar() != null) getActionBar().hide();

        //让屏幕是一直亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        // 系统不进入休眠
        PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TAG");
        mWakeLock.acquire();

        //初始化UI
        wifiTxtView = (TextView) findViewById(R.id.main_tv_wifi_status);
        recordTxtView = (TextView) findViewById(R.id.main_tv_record_status);
        mainTvOrigin = (TextView) findViewById(R.id.main_tv_origin);
        mainIvRecord = (ImageView) findViewById(R.id.main_iv_record);
        mainRlRecord = (RelativeLayout) findViewById(R.id.main_rl_record);
        ivBtnCH = (RadioButton) findViewById(R.id.main_rb_cn);
        ivBtnEN = (RadioButton) findViewById(R.id.main_rb_en);
        mainRlSwitch = (RelativeLayout) findViewById(R.id.main_rl_switch);
        mainTvSwitch = (TextView) findViewById(R.id.main_tv_switch);
        mainTvBattery = (TextView) findViewById(R.id.main_tv_battery);
        mainIvCircle = (ImageView) findViewById(R.id.main_iv_circle);
        mainIvBattery = (ImageView) findViewById(R.id.main_iv_battery);
        mainRlRecord.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        isKeyUp = false;
                        if (wifiBinder != null) {
                            wifiBinder.requestVoiceStart();
                        }
                        mHandler.sendEmptyMessageDelayed(101, 300);
                        onClickDownAnimator(mainIvRecord, mainIvCircle);
                        mainTvOrigin.setVisibility(View.GONE);
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                        isKeyUp = true;
                        if (wifiBinder != null) {
                            wifiBinder.requestVoiceStop();
                        }
                        mainRlRecord.setClickable(false);
                        mainRlRecord.setEnabled(false);
                        transBinder.stopContinuousRecord();
                        mHandler.removeCallbacksAndMessages(null);
                        onClickUpAnimator(mainIvRecord, mainIvCircle);
                        mainTvOrigin.setVisibility(View.VISIBLE);
                        mHandler.sendEmptyMessageDelayed(100, 500);

                        break;
                }
                return true;
            }
        });

        mainRlSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showRecoDialog();
            }
        });

        //初始化音量管理
        audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        audioManager.setMode(AudioManager.MODE_NORMAL);
        audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        LogUtil.d(TAG, "音频模式" + audioManager.getMode() + " 震动模式:" + audioManager.getRingerMode());

        //初始化按键
        setVolumeControlStream(AudioManager.STREAM_SYSTEM);

       /* //启动蓝牙
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            LogUtil.i(TAG, "No Bluetooth Device");
            finish();
        }
        if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
            *//*Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enabler, 0);*//*
            //不做提示，强行打开
            bluetoothAdapter.enable();
        }
        if (!bluetoothAdapter.isEnabled()) {
            LogUtil.i(TAG, "Bluetooth Enable Error");
            //finish();
        }*/

        //初始化语音参数
        char language = getString(R.string.language_c).charAt(0);
        isCH2EN = language == 'c';
        mainTvSwitch.setText(getString(R.string.text_language_ch));

        //初始化翻译的地址
        String orgServerPath = getString(R.string.server_addr);
        String hzServerPath = getString(R.string.server_addr_hangzhou);
        String path = hzServerPath + ":" + getResources().getInteger(R.integer.server_port)
                + "/" + getString(R.string.servlet_path);
        AZTClient.setServerPath(path);

        //启动服务
        //绑定蓝牙服务
       /* Intent btService = new Intent(MainActivity.this, BTService.class);
        bindService(btService, this, Context.BIND_AUTO_CREATE);*/
        //启动翻译服务
        Intent intent = new Intent(this, TranslationService.class);
        bindService(intent, this, Context.BIND_AUTO_CREATE);
        //绑定WIFI服务
        Intent wifiService = new Intent(MainActivity.this, WIFIService.class);
        bindService(wifiService, this, Context.BIND_AUTO_CREATE);

        //注册注册广播接收者
        registerReceiver(receiver, getIntentFilter());


        //电池相关
        mBatteryFilter = new IntentFilter();
        mBatteryFilter.addAction(Intent.ACTION_BATTERY_CHANGED);

        registerReceiver(mBatteryReceiver, mBatteryFilter);


        //播放提示声音
        PromptUtil.poolPlay(this, R.raw.application_started);

        LogUtil.i(TAG, "MainActivity started when " + SocketUtils.formatCurrentTime());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(this);
        try {
            unregisterReceiver(receiver);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        try {
            unregisterReceiver(mBatteryReceiver);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

        if (mWakeLock != null) {
            mWakeLock.release();
            mWakeLock = null;
        }
        LogUtil.e(TAG, "Destroy When " + SocketUtils.formatCurrentTime());
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        if (service instanceof TranslationService.MyBinder) {
            transBinder = (TranslationService.MyBinder) service;
            transService = ((TranslationService.MyBinder) service).getService();
        } else if (service instanceof WIFIService.WifiBinder) {
            wifiBinder = (WIFIService.WifiBinder) service;
            wifiService = ((WIFIService.WifiBinder) service).getService();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        LogUtil.eee(name.getClassName() + " has disconnected");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        LogUtil.i(TAG, "Key Code " + keyCode);
        switch (keyCode) {
            case KEY_RECORD_ACTION:
                stopRecord();
                return true;
            case KEY_LANGUAGE_ACTION:
                // TODO 修改语言
                //updateLanguage();
                return true;
            case KEY_VOLUME_UP:
                LogUtil.d(TAG, "KEY_VOLUME_UP");
                //音量增大
                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
                return true;
            case KEY_VOLUME_DOWN:
                LogUtil.d(TAG, "KEY_VOLUME_DOWN");
                //音量减小
                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
                return true;
            case KeyEvent.KEYCODE_POWER:
                LogUtil.d(TAG, "KEYCODE_POWER");
                doPowerOff(event.getRepeatCount());
                return false;
            case KeyEvent.KEYCODE_BACK:
                LogUtil.d(TAG, "KEYCODE_BACK");
                android.os.Process.killProcess(android.os.Process.myPid());
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        LogUtil.i(TAG, "onKeyUp");
        switch (keyCode) {
            case KeyEvent.KEYCODE_POWER:
                poweroff = false;
                return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    private IntentFilter getIntentFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.WIFI_BORADCAST_ACTION);
        filter.addAction(Constants.TRANS_BORADCAST_ACTION);
        return filter;
    }

    /**
     * 开始录音
     */
    private void startRecord() {
        stopAll();
        if (transBinder != null) transBinder.startRecord(isCH2EN);
    }

    /**
     * 开始连续录音
     */
    private void startContinuousRecord() {
        stopAll();
        if (transBinder != null) transBinder.startContinuousRecord(isCH2EN);
    }

    /**
     * 结束录音
     */
    private void stopRecord() {
        if (transBinder != null) transBinder.stopRecord();
    }

    /**
     * 结束录音,且不保存，不识别
     */
    private void cancelRecord() {
        if (transBinder != null) transBinder.cancelRecord();
    }

    /**
     * 停止录音,播放,停止合成及消息队列
     */
    private void stopAll() {
        if (transBinder != null) transBinder.stopAll();
        recordTxtView.setVisibility(View.INVISIBLE);
    }

    /**
     * 间隔时间销毁
     */
    private void doPowerOff(int repeat) {
        int interval = getResources().getInteger(R.integer.power_off_interval);
        int exit_interval = getResources().getInteger(R.integer.wifi_exit_interval);

        long previoustime = 0;
        if (repeat == 0) {
            previoustime = System.currentTimeMillis();
        }
        if (System.currentTimeMillis() - previoustime > exit_interval)
            wifiExit = true;

        if (wifiExit) {
            //btService.sendWifiExit();
            if (wifiBinder != null) {
                wifiBinder.sendExit();
            }
        }

        if (System.currentTimeMillis() - previoustime > interval)
            poweroff = true;

        if (poweroff) {
            // TODO: 2016/1/18 关机
            PromptUtil.poolPlay(this, R.raw.application_closing);
            // TODO: 2016/1/25  关机广播
        }
    }

    /**
     * 语音输入的提示框
     */
    @SuppressLint("InflateParams")
    private void showRecoDialog() {
        if (switchDialog == null) {
            switchDialog = getCircularCornerDialog(this);
            settingsRgSwitch = (RadioGroup) switchDialog.findViewById(R.id.settings_rg_switch);
            settingsIvBack = (ImageView) switchDialog.findViewById(R.id.settings_iv_back);
            settingsRlBack = (RelativeLayout) switchDialog.findViewById(R.id.settings_rl_back);
            settingsBtCh = (RadioButton) switchDialog.findViewById(R.id.settings_bt_ch);
            settingsBtEn = (RadioButton) switchDialog.findViewById(R.id.settings_bt_en);

            if (isCH2EN) {
                settingsRgSwitch.check(R.id.settings_bt_ch);
            } else {
                settingsRgSwitch.check(R.id.settings_bt_en);
            }

            settingsRgSwitch.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    switch (checkedId) {
                        case R.id.settings_bt_ch:

                            if (wifiBinder != null) {
                                isCH2EN = true;
                                wifiBinder.changeLocalLanguage(true);
                                wifiBinder.changeServerLanguage('c');
                                mainTvSwitch.setText(getString(R.string.text_language_ch));
                            }

                            break;
                        case R.id.settings_bt_en:
                            if (wifiBinder != null) {
                                isCH2EN = false;
                                wifiBinder.changeLocalLanguage(false);
                                wifiBinder.changeServerLanguage('e');
                                mainTvSwitch.setText(getString(R.string.text_language_en));
                            }

                            break;
                    }
                }
            });

            settingsRlBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switchDialog.cancel();
                }
            });
        }
        switchDialog.show();
    }

    /**
     * 返回一个默认内容的dialog
     */
    public Dialog getCircularCornerDialog(Context context) {
        Dialog dialog = new Dialog(context, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.dialog_settings, null);
        dialog.setContentView(view);
        return dialog;
    }


    /**
     * service发送的广播
     */
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constants.TRANS_BORADCAST_ACTION)) {
                String option = intent.getStringExtra(Constants.BORADCAST_INTENT_OPTION);
                switch (option) {
                    case TranslationService.EXTRA_TEMP_RESULT_CHANGED:
                        break;
                    case TranslationService.EXTRA_TRANSLATED:
                        //VoiceInfo voiceInfo = (VoiceInfo) intent.getSerializableExtra("voiceInfo");
                        break;
                    case TranslationService.EXTRA_NO_RESULT:
                        break;
                    case TranslationService.EXTRA_RECOGNIZE_FINISHED:
                        break;
                    case TranslationService.EXTRA_RECOGNIZED_RESULT:
                        VoiceInfo voiceInfo = (VoiceInfo) intent.getSerializableExtra("voiceInfo");
                        if (voiceInfo != null) {
                            sendVoice(voiceInfo);
                            mainTvOrigin.setText(voiceInfo.getOrgContent());
                        }
                        break;
                }
            } else if (intent.getAction().equals(Constants.WIFI_BORADCAST_ACTION)) {
                String option = intent.getStringExtra(Constants.BORADCAST_INTENT_OPTION);
                switch (option) {
                    case UdpManager.KEY_GROUP_CONNECTED_STATUS:
                        LogUtil.i(TAG, "WIFI已连接");
                        wifiTxtView.setText("已连接");
                        break;
                    case UdpManager.KEY_GROUP_CONNECTING_STATUS:
                        LogUtil.i(TAG, "WIFI连接中");
                        wifiTxtView.setText("连接中");
                        break;
                    case UdpManager.KEY_GROUP_DISCONNECT_STATUS:
                        LogUtil.i(TAG, "WIFI未连接");
                        wifiTxtView.setText("未连接");
                        break;
                    case UdpManager.KEY_HANDLER_ORG_VOICE_DATA:
                        LogUtil.i(TAG, "合成服务端返回结果");
                        // 处理翻译
                        // TODO: 2016/1/18   从WifiService接受文字，暂不接收语音
                        // myVoice.playRecord(WIFIService.serverVoiceData);
                        VoiceInfo voiceInfo = (VoiceInfo) intent.getSerializableExtra(UdpManager.INTENT_TRANSFER_VOICE_DATA);
                        if (transBinder != null)
                            transBinder.synthesizeContent(voiceInfo.getTranContent(), !isCH2EN);
                        break;
                    case UdpManager.KEY_HANDLER_ORG_VOICE_TEXT_ERROR:
                        LogUtil.i(TAG, "服务端无返回结果");
                        break;
                    case UdpManager.KEY_VOICE_RESPONSE_PERMIT:
                        LogUtil.i(TAG, "请进行语音输入");
                        ToastUtil.showTip("请说话");
                        if (!isKeyUp) {
                            startContinuousRecord();
                            permitAnimator(mainIvRecord, mainIvCircle);
                        } else {
                            /*if (wifiBinder != null) {
                                wifiBinder.requestVoiceStop();
                            }*/
                        }
                        break;
                    case UdpManager.KEY_VOICE_RESPONSE_PREVENT:
                        LogUtil.i(TAG, "服务端阻止了语音输入");
                        ToastUtil.showTip("你无法进行语音输入");
                        if (!isKeyUp) {
                            preventAnimator(mainIvRecord, mainIvCircle);
                        }
                        mainRlRecord.setClickable(true);
                        mainRlRecord.setEnabled(true);
                        break;
                    case UdpManager.KEY_VOICE_RESPONSE_FINISH:
                        LogUtil.i(TAG, "已经通知服务端停止");
                        ToastUtil.showTip("已经通知服务器停止");
                        if (!isKeyUp) {
                            preventAnimator(mainIvRecord, mainIvCircle);
                        }
                        mainRlRecord.setClickable(true);
                        mainRlRecord.setEnabled(true);
                        break;
                    case UdpManager.KEY_LANGUAGE_CHANGED:
                        LogUtil.i(TAG, "已经通知服务端改变语言");
                        ToastUtil.showTip("输入语音已经改变");
                        break;
                }
            }
        }
    };

    /**
     * 发送数据到server端
     */
    private void sendVoice(final VoiceInfo voiceInfo) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (wifiBinder != null) {
                    wifiBinder.sendVoiceData(voiceInfo);
                }
            }
        }).start();
    }

    private void onClickDownAnimator(ImageView view1, ImageView view2) {
        view1.setBackgroundResource(R.mipmap.ic_record);

        cancelOnClickDownAnimator();
        cancelOnClickUpAnimator();
        cancelPermitAnimationSet();
        cancelPreventAnimator();

        if (onClickDownAnimationSet == null) {
            ObjectAnimator anim1 = ObjectAnimator
                    .ofFloat(view1, "scaleX", 1.0F, 1.7F)
                    .setDuration(500);
            ObjectAnimator anim2 = ObjectAnimator
                    .ofFloat(view1, "scaleY", 1.0F, 1.7F)
                    .setDuration(500);
            ObjectAnimator anim3 = ObjectAnimator
                    .ofFloat(view1, "translationY", 0, -60)
                    .setDuration(500);
            ObjectAnimator anim4 = ObjectAnimator
                    .ofFloat(view2, "translationY", 0, -60)
                    .setDuration(500);
            onClickDownAnimationSet = new AnimatorSet();
            onClickDownAnimationSet.playTogether(anim1, anim2, anim3, anim4);
        }
        onClickDownAnimationSet.start();
    }

    private void cancelOnClickDownAnimator() {
        if (onClickDownAnimationSet != null && onClickDownAnimationSet.isRunning()) {
            onClickDownAnimationSet.cancel();
        }
    }

    private void onClickUpAnimator(ImageView view1, ImageView view2) {
        view2.setVisibility(View.INVISIBLE);
        view1.setBackgroundResource(R.mipmap.ic_record);

        cancelOnClickDownAnimator();
        cancelPermitAnimationSet();
        cancelPreventAnimator();

        if (onClickUpAnimationSet == null) {
            ObjectAnimator anim1 = ObjectAnimator
                    .ofFloat(view1, "scaleX", 1.7F, 1.0F)
                    .setDuration(100);
            ObjectAnimator anim2 = ObjectAnimator
                    .ofFloat(view1, "scaleY", 1.7F, 1.0F)
                    .setDuration(100);
            ObjectAnimator anim3 = ObjectAnimator
                    .ofFloat(view1, "translationY", -60, 0)
                    .setDuration(500);
            ObjectAnimator anim4 = ObjectAnimator
                    .ofFloat(view2, "translationY", 0, -60)
                    .setDuration(500);

            onClickUpAnimationSet = new AnimatorSet();
            onClickUpAnimationSet.playTogether(anim1, anim2, anim3, anim4);
        }
        onClickUpAnimationSet.start();
    }

    private void cancelOnClickUpAnimator() {
        if (onClickUpAnimationSet != null && onClickUpAnimationSet.isRunning()) {
            onClickUpAnimationSet.cancel();
        }
    }

    private void permitAnimator(ImageView view1, ImageView view2) {
        view2.setVisibility(View.VISIBLE);
        view1.setBackgroundResource(R.mipmap.ic_record);

        cancelOnClickUpAnimator();
        cancelPreventAnimator();

        if (permitAnimationSet == null) {
            ObjectAnimator anim1 = ObjectAnimator
                    .ofFloat(view2, "scaleX", 1.5F, 2.5F).setDuration(1000);
            ObjectAnimator anim2 = ObjectAnimator
                    .ofFloat(view2, "scaleY", 1.5F, 2.5F).setDuration(1000);
            ObjectAnimator anim3 = ObjectAnimator
                    .ofFloat(view2, "alpha", 1.5F, 0.0F).setDuration(1000);

            anim1.setRepeatCount(ValueAnimator.INFINITE);
            anim2.setRepeatCount(ValueAnimator.INFINITE);
            anim3.setRepeatCount(ValueAnimator.INFINITE);

            permitAnimationSet = new AnimatorSet();
            permitAnimationSet.playTogether(anim1, anim2, anim3);
        }
        permitAnimationSet.start();
    }

    private void cancelPermitAnimationSet() {
        if (permitAnimationSet != null && permitAnimationSet.isRunning()) {
            permitAnimationSet.cancel();
        }
    }

    private void preventAnimator(ImageView view1, ImageView view2) {
        cancelOnClickUpAnimator();
        cancelPermitAnimationSet();

        view2.setVisibility(View.INVISIBLE);
        view1.setBackgroundResource(R.mipmap.ic_record_prevent);
    }


    private void cancelPreventAnimator() {

    }

    /**
     * 电量消息处理
     */
    private BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            int status = intent.getIntExtra("status", 0);
            int health = intent.getIntExtra("health", 0);
            boolean present = intent.getBooleanExtra("present", false);
            int level = intent.getIntExtra("level", 0);
            int scale = intent.getIntExtra("scale", 0);
            int icon_small = intent.getIntExtra("icon-small", 0);
            int plugged = intent.getIntExtra("plugged", 0);
            int voltage = intent.getIntExtra("voltage", 0);
            int temperature = intent.getIntExtra("temperature", 0);
            String technology = intent.getStringExtra("technology");
            String statusString = "";
            switch (status) {
                case BatteryManager.BATTERY_STATUS_UNKNOWN:
                    statusString = "unknown";
                    break;
                case BatteryManager.BATTERY_STATUS_CHARGING:
                    statusString = "charging";
                    mainIvBattery.setImageResource(R.mipmap.ic_charging_battery);
                    mainTvBattery.setText(getString(R.string.text_battery, level));
                    break;
                case BatteryManager.BATTERY_STATUS_DISCHARGING:
                    statusString = "discharging";
                    mainIvBattery.setImageResource(R.drawable.status_battery);
                    mainIvBattery.getDrawable().setLevel(level);
                    mainTvBattery.setText(getString(R.string.text_battery, level));
                    break;
                case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                    statusString = "not charging";
                    break;
                case BatteryManager.BATTERY_STATUS_FULL:
                    statusString = "full";
                    break;
            }
            String healthString = "";
            switch (health) {
                case BatteryManager.BATTERY_HEALTH_UNKNOWN:
                    healthString = "unknown";
                    break;
                case BatteryManager.BATTERY_HEALTH_GOOD:
                    healthString = "good";
                    break;
                case BatteryManager.BATTERY_HEALTH_OVERHEAT:
                    healthString = "overheat";
                    break;
                case BatteryManager.BATTERY_HEALTH_DEAD:
                    healthString = "dead";
                    break;
                case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
                    healthString = "voltage";
                    break;
                case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
                    healthString = "unspecified failure";
                    break;
            }
            String acString = "";
            switch (plugged) {
                case BatteryManager.BATTERY_PLUGGED_AC:
                    acString = "plugged ac";
                    break;
                case BatteryManager.BATTERY_PLUGGED_USB:
                    acString = "plugged usb";
                    break;
            }
            LogUtil.i("cat", statusString);
            LogUtil.i("cat", healthString);
            LogUtil.i("cat", String.valueOf(present));
            LogUtil.i("cat", String.valueOf(level));
            LogUtil.i("cat", String.valueOf(scale));
            LogUtil.i("cat", String.valueOf(icon_small));
            LogUtil.i("cat", acString);
            LogUtil.i("cat", String.valueOf(voltage));
            LogUtil.i("cat", String.valueOf(temperature));
            LogUtil.i("cat", technology);
            //要看看是不是我们要处理的消息
            if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
                //电池电量，数字
                LogUtil.d("Battery", "" + intent.getIntExtra("level", 0));
                //电池最大容量
                LogUtil.d("Battery", "" + intent.getIntExtra("scale", 0));
                //电池伏数
                LogUtil.d("Battery", "" + intent.getIntExtra("voltage", 0));
                //电池温度
                LogUtil.d("Battery", "" + intent.getIntExtra("temperature", 0));
                //电池状态，返回是一个数字
                // BatteryManager.BATTERY_STATUS_CHARGING 表示是充电状态
                // BatteryManager.BATTERY_STATUS_DISCHARGING 放电中
                // BatteryManager.BATTERY_STATUS_NOT_CHARGING 未充电
                // BatteryManager.BATTERY_STATUS_FULL 电池满
                LogUtil.d("Battery", "ss" + intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_CHARGING));
                //充电类型 BatteryManager.BATTERY_PLUGGED_AC 表示是充电器，不是这个值，表示是 USB
                LogUtil.d("Battery", "" + intent.getIntExtra("plugged", 0));
                //电池健康情况，返回也是一个数字
                //BatteryManager.BATTERY_HEALTH_GOOD 良好
                //BatteryManager.BATTERY_HEALTH_OVERHEAT 过热
                //BatteryManager.BATTERY_HEALTH_DEAD 没电
                //BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE 过电压
                //BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE 未知错误
                LogUtil.d("Battery", "" + intent.getIntExtra("health", BatteryManager.BATTERY_HEALTH_UNKNOWN));
            }
        }
    };
}
